package com.lxk.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.lxk.pojo.RechargeOrder;
import com.lxk.pojo.Users;
import com.lxk.service.RechargeOrderService;
import com.lxk.service.UsersService;
import com.lxk.util.CodeUtil;
import com.lxk.util.exception.GlobalException;
import com.lxk.util.wxpay.MiniWxPayConfig;
import com.lxk.util.wxpay.MyWxPayUtil;
import com.lxk.vo.result.CodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JohnSoybean
 * @create 2020/4/20 13:34
 * @description 微信支付控制器
 */
@Slf4j
@RestController
@RequestMapping("/wxpay")
public class WxPayController {

    @Autowired
    private RechargeOrderService rechargeOrderService;
    @Autowired
    private UsersService usersService;

    /**
     * 返回成功xml
     */
    private String resSuccessXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

    /**
     * 返回失败xml
     */
    private String resFailXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[return_code_err]]></return_msg></xml>";


    /**
     * 小程序端 微信支付接口
     * @return
     * @throws Exception
     */
    @PostMapping(value="/pay")
    @Transactional
    public Map<String, String> miniPay(HttpServletRequest req, Long rechargeOrderId) throws Exception {
        //获取openid
        Long userId = (Long) req.getAttribute("userId");
        Users users = usersService.getById(userId);
        if (users == null) throw new GlobalException(CodeMsg.USER_NOT_EXIST);
        String openid = users.getOpenid();
        //生成交易单号
        String orderNo = CodeUtil.generateOrderNumber();
        log.info("==================微信小程序下单,商户订单号为：" + orderNo);
        //获取订单信息 判断重复支付
        RechargeOrder order = rechargeOrderService.getById(rechargeOrderId);
        if (order == null) throw new GlobalException(CodeMsg.ORDER_NOT_EXIST);
        if (order.getRechargeOrderProgress() != 0) throw new GlobalException(CodeMsg.REPEAT_PAY);
        //更新交易单号
        RechargeOrder updOrder = new RechargeOrder();
        updOrder.setRechargeOrderId(order.getRechargeOrderId());
        updOrder.setRechargeOrderNo(orderNo);
        rechargeOrderService.updateById(updOrder);
        //获取支付价格
        Integer rechargePrice = order.getRechargePrice();
        if (rechargePrice == null) throw new GlobalException(CodeMsg.ORDER_PRICE_ERR);
        String pricePayStr = String.valueOf(rechargePrice);
        if (pricePayStr == null) throw new GlobalException(CodeMsg.ORDER_PRICE_ERR);
        log.info("WXPAY - 价格：" + pricePayStr);

        //发起微信支付
        MiniWxPayConfig config = new MiniWxPayConfig();
        WXPay wxpay = new WXPay(config, WXPayConstants.SignType.MD5, false);
        Map<String, String> data = new HashMap<>();
        data.put("body", "NoX棒球零售商城");
        data.put("out_trade_no", orderNo);
        data.put("device_info", "WEB");
        data.put("fee_type", "CNY");
//FIXME: 已复原价格
        data.put("total_fee", pricePayStr);
//        data.put("total_fee", "1");
        data.put("spbill_create_ip", MyWxPayUtil.getRemoteHost());
        data.put("notify_url", MyWxPayUtil.notify_url);
        data.put("trade_type", "JSAPI");  // 小程序支付此处同公众号支付
        data.put("openid", openid); //JSAPI类型 此参数必传

        Map<String, String> resp = null;
        Map<String, String> result = null;
        try {
            resp = wxpay.unifiedOrder(data);
            log.info("resp:"+resp);
            result = MyWxPayUtil.respToResult(resp);
            result.put("outTradeNo", orderNo);
            log.info("result:"+result);
        } catch (Exception e) {
            log.info("微信支付调用失败"+e);
            throw new GlobalException(CodeMsg.WXPAY_READY_ERR);
        }
        return result;
    }


    /**
     * 接收微信回调通知接口，成功则修订单改状态，并反馈给微信
     * 将业务逻辑独立于回调返回参数 并对业务逻辑出现的异常进行数据库记录
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/afterpay", produces = {"application/xml; charset=UTF-8"})
    @ResponseBody
    public String notify(HttpServletRequest request) {
        boolean flag = false;
        ServletInputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        String out_trade_no = "";	//回调是否成功
        String result_code = "";	//支付结果 是否成功

        try {
            is = request.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            StringBuilder stb = new StringBuilder();
            String s = "";
            while ((s = br.readLine()) != null) {
                stb.append(s);
            }
            Document document = DocumentHelper.parseText(stb.toString());
            String return_code = "";
            List<Element> returnCodeList = document.selectNodes("//return_code");
            for (Element element : returnCodeList) {
                return_code = element.getText();	//回调结果
            }
            if (return_code.equals("SUCCESS")) {    //回调返回成功
                List<Element> prepayIdList = document.selectNodes("//out_trade_no");
                for (Element element : prepayIdList) {
                    out_trade_no = element.getText();
                }
                log.info("out_trade_no: "+out_trade_no);
                //业务逻辑
                if (null!=out_trade_no && !out_trade_no.equals("")) {
                    flag = true;
                    log.info("Notify check over.");

                    //判断是否支付成功
                    List<Element> resultCodeList = document.selectNodes("//result_code");
                    for (Element element : resultCodeList) {
                        result_code = element.getText();
                    }
                    log.info("result_code: "+result_code);
                    //业务逻辑放在外面
                }
            }
        } catch (Exception e) {
            flag = false;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                flag = true;
            }
        }

        //业务逻辑处理
        try {
            if (null!=out_trade_no && !out_trade_no.equals("")) {
                if(result_code.equals("SUCCESS")) { //支付成功
                    //充值
                    rechargeOrderService.rechargeCallBackSuccess(out_trade_no);
                }
            }
        } catch(Exception e){
            log.error("微信回调业务处理报错：" + e);
        }

        if (flag) {
            log.info("notify_SUCCESS！");
            return resSuccessXml;
        } else {
            log.info("notify_FAILED！");
            return resFailXml;
        }
    }

}
